const app = getApp();

Page({
  data: {
    records: [],
    filteredRecords: [],
    sortIndex: 0,
    filterIndex: 0,
    sortOptions: ['按时间倒序', '按时间正序', '按冲突等级'],
    filterOptions: ['全部', '已解决', '未解决', '进行中']
  },
  
  onShow() {
    this.loadRecords();
  },
  
  loadRecords() {
    const records = app.getAllRecords();
    const formattedRecords = records.map(record => this.formatRecord(record));
    
    this.setData({
      records: formattedRecords,
      filteredRecords: this.filterRecords(formattedRecords, this.data.filterIndex),
    });
  },
  
  formatRecord(record) {
    const dateObj = new Date(record.date);
    const formattedDate = `${dateObj.getFullYear()}-${(dateObj.getMonth() + 1).toString().padStart(2, '0')}-${dateObj.getDate().toString().padStart(2, '0')}`;
    
    // 冲突等级标签
    const conflictLabels = ['轻微', '低', '中等', '高', '严重'];
    const conflictLabel = conflictLabels[record.conflictLevel - 1] || '中等';
    
    // 状态文本
    const statusTexts = {
      resolved: '已解决',
      unresolved: '未解决',
      'in-progress': '进行中'
    };

    return {
      ...record,
      formattedDate,
      conflictLabel,
      statusText: statusTexts[record.status] || '已解决'
    };
  },
  
  // 改变排序方式
  changeSort(e) {
    const index = e.detail.value;
    this.setData({ sortIndex: index });
    this.sortRecords(index);
  },
  
  // 改变筛选条件
  changeFilter(e) {
    const index = e.detail.value;
    this.setData({ 
      filterIndex: index,
      filteredRecords: this.filterRecords(this.data.records, index)
    });
  },
  
  // 筛选记录
  filterRecords(records, filterIndex) {
    if (filterIndex == 0) return records;
    
    const statusMap = {
      1: 'resolved',
      2: 'unresolved',
      3: 'in-progress'
    };
    
    const status = statusMap[filterIndex];
    return records.filter(record => record.status === status);
  },
  
  // 排序记录
  sortRecords(sortIndex) {
    let sortedRecords = [...this.data.records];
    
    switch (parseInt(sortIndex)) {
      case 0: // 按时间倒序
        sortedRecords.sort((a, b) => new Date(b.date) - new Date(a.date));
        break;
      case 1: // 按时间正序
        sortedRecords.sort((a, b) => new Date(a.date) - new Date(b.date));
        break;
      case 2: // 按冲突等级
        sortedRecords.sort((a, b) => b.conflictLevel - a.conflictLevel);
        break;
    }
    
    this.setData({
      records: sortedRecords,
      filteredRecords: this.filterRecords(sortedRecords, this.data.filterIndex)
    });
  },
  
  // 导航到详情页
  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/record-detail/record-detail?id=${id}`
    });
  },
  
  // 导航到新增记录页
  navigateToAddRecord() {
    wx.navigateTo({
      url: '/pages/add-record/add-record'
    });
  }
});